package com.gxa.user.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gxa.user.dto.Keywords;
import com.gxa.user.dto.MyParam;
import com.gxa.user.exception.SystemException;
import com.gxa.user.service.UploadService;
import com.gxa.user.validator.MyValidator;
import dto.ResultDTO;
import entity.City;
import entity.Member;
import com.gxa.user.dao.MemberDao;
import com.gxa.user.service.MemberService;
import group.UserAdd;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import param.MailDTO;
import util.MD5Util;
import util.Response;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import java.sql.Timestamp;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * (Member)表服务实现类
 *
 * @author makejava
 * @since 2021-05-10 19:01:13
 */
@Service("memberService")
public class MemberServiceImpl implements MemberService {
    @Resource
    private MemberDao memberDao;

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private UploadService uploadService;

    @Autowired
    private MyValidator myValidator;

    /**
     * 从redis中取验证码
     */
    @Resource(name = "objectRedisTemplate")
    private RedisTemplate<String,Object> redisTemplate;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 通过ID查询单条数据
     *
     * @param memberId 主键
     * @return 实例对象
     */
    @Override
    public Member queryById(Integer memberId) {
        return this.memberDao.queryById(memberId);
    }




    /**
     * 修改数据
     *
     * @param member 实例对象
     * @return 实例对象
     */
    @Override
    public Member update(Member member) {
        this.memberDao.update(member);
        return this.queryById(member.getMemberId());
    }

    /**
     * 通过主键删除数据
     *
     * @param memberId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer memberId) {
        return this.memberDao.deleteById(memberId) > 0;
    }

    @Override
    public PageInfo findAll(MyParam param) {
        PageHelper.startPage(param.getPage(),param.getLimit());
        List<Member> memberList = memberDao.findAll(param);
        PageInfo<Member> pageInfo = new PageInfo<>(memberList);
        return pageInfo;
    }

    /**
     * 删除用户
     * @param memberId
     * @return
     */
    @Override
    public ResultDTO delete(Integer memberId) {
        int i = memberDao.delete(memberId);
        if (i>0){
            return new ResultDTO(200,"删除成功");
        }
        return new ResultDTO(1001,"删除失败");
    }

    /**
     * 禁用用户
     * @param
     * @return
     */
    @Override
    public ResultDTO disable(Integer memberId) {
        Member member = memberDao.queryById(memberId);
        if (member.getMemberStatus() == 1){
            return new ResultDTO(1001,"用户已禁用，请勿重复操作!");
        }
        memberDao.disable(memberId);
        return new ResultDTO(200,"禁用成功");
    }

    @Override
    public ResultDTO able(Integer memberId) {
        Member member = memberDao.queryById(memberId);
        if (member.getMemberStatus() == 0){
            return new ResultDTO(1001,"用户已启用，请勿重复操作!");
        }
        memberDao.able(memberId);
        return new ResultDTO(200,"启用成功");
    }


    /**
     * 根据id查询用户是否存在
     */
    @Override
    public ResultDTO query(Integer id) {
        Member member = memberDao.query(id);
        if (member == null) {
            return new ResultDTO(1001,"error");
        }
        return new ResultDTO(200,"success",member);
    }

    /**
     * 根据传入对象，判断传入信息是否存在
     */
    @Override
    public ResultDTO queryMember(Member member) {
        System.out.println(member);
        Member newMember = memberDao.queryMember(member);
        if (newMember == null) {
            return new ResultDTO(1001,"error");
        }
        Integer memberId = newMember.getMemberId();
        Member member1 = new Member();
        member1.setMemberId(memberId);
        System.out.println("----------------------------------------------");
        System.out.println(newMember);
        System.out.println("-------------------------------------------------");
        return new ResultDTO(200,"success",member1);
    }

    /**
     * 根据关键字查询
     * @param keywords
     * @return
     */
    @Override
    public ResultDTO queryByKeywords(Keywords keywords) {
        if (keywords != null) {
            PageHelper.startPage(keywords.getPage(),keywords.getLimit());
            List<Member> members = memberDao.queryByKeywords(keywords);
            PageInfo<Member> pageInfo = new PageInfo<>(members);
            if (members.size() == 0){
                return new ResultDTO(1003,"没有符合该条件的信息。");
            }
            return new ResultDTO(200,"查询成功",pageInfo);
        }
        return new ResultDTO(1001,"查询失败");

    }

    /**
     * 根据用户id查询所有信息，包括角色等
     * @param memberId
     * @return
     */
    @Override
    public ResultDTO findAllById(Integer memberId) {
        Member member = memberDao.findAllById(memberId);
        if (member == null){
            return new ResultDTO(1002,"该用户不存在");
        }
        return new ResultDTO(200,"success",member);
    }

    /**
     * 根据用户id查询所有信息，包括角色等
     * @param memberId
     * @return
     */
    @Override
    public ResultDTO findAllByTt(Integer memberId) {
        Member member = memberDao.findAllByTt(memberId);
        if (member == null){
            return new ResultDTO(1002,"该用户不存在");
        }
        return new ResultDTO(200,"success",member);
    }


    /**
     * 查询管理员邮箱
     * @return
     */
    @Override
    public ResultDTO selectEmail() {
        String email = memberDao.selectEmail();
        if (email == null){
            return new ResultDTO(1002,"该用户不存在");
        }
        return new ResultDTO(200,"success",email);
    }

    /**
     * 根据部门id和角色id查询
     */
    @Override
    public ResultDTO findByDeptIdAndRoleId(Integer deptId, Integer roleId) {
        Member member = memberDao.findByDeptIdAndRoleId(deptId, roleId);
        if (member == null){
            return new ResultDTO(1002,"该用户不存在");
        }
        return new ResultDTO(200,"success",member);
    }

    /**
     * 查询总经理
     * @return
     */
    @Override
    public ResultDTO findBoss() {
        Member boss = memberDao.findBoss();
        if (boss == null){
            return new ResultDTO(1002,"没有总经理");
        }
        return new ResultDTO(200,"success",boss);
    }


    /**
     * 根据城市Id查城市
     */
    @Override
    public ResultDTO findByCityId(Integer cityId) {
        City city = memberDao.findByCityId(cityId);
        if (city == null){
            return new ResultDTO(1002,"不存在该城市");
        }
        return new ResultDTO(200,"success",city);
    }

    /**
     * 查询城市和城市Id
     */
    @Override
    public ResultDTO findCityAndCityId() {
        List<City> cityAndCityId = memberDao.findCityAndCityId();
        if (cityAndCityId != null) {
            return new ResultDTO(200,"success",cityAndCityId);
        }
        return new ResultDTO(1001,"error");
    }

    /**
     * 增加员工
     * @param member
     * @return
     */
    @Override
    public ResultDTO insertUser(Member member) {

        myValidator.validate(member, UserAdd.class);
        List<Member> list = memberDao.findAllNoPage();
        for (Member member1 : list) {
            System.out.println(member1);
            if (member1.getIdCardNum().equals(member.getIdCardNum())) {
                return new ResultDTO(1002,"该用户已存在，请勿重新添加");
            }
        }
//        String pwd = MD5Util.MD55(member.getMemberPwd());
//        member.setMemberPwd(pwd);
        member.setCreateTime(new Timestamp(System.currentTimeMillis()));
        member.setMemberPwd("123456");
        int insert = memberDao.insert(member);
        if (insert>0) {
            return new ResultDTO(200,"添加成功");
        }
        return new ResultDTO(1001,"添加失败");
    }


    /**
     * 输入原密码改密码
     */
    @Override
    public ResultDTO updatePassword(Integer memberId, String memberPwd, String newPwd) {
        //根据传入id查询修改的是哪个用户的密码
        Member member = memberDao.queryById(memberId);
        //判断输入的原密码是否正确
        //如果输入正确
        if (member.getMemberPwd().equals(memberPwd)) {
            memberDao.updatePwd(memberId,newPwd);
            return new ResultDTO(200,"修改成功");
        }
        return new ResultDTO(1003,"原密码错误，请重新输入");
    }

    /**
     * 发邮件改密码
     */
    @Override
    public ResultDTO updatePwd(Integer memberId,String newPwd,String code) {
        //根据传入id查询修改的是哪个用户的密码
        Member member = memberDao.queryById(memberId);
        //从redis取验证码，如果redis为空，验证码过期
        String  pop = (String) redisTemplate.opsForSet().pop("userCode:" + member.getMemberEmail());
        System.out.println(pop);
        if (pop == null){
            return new ResultDTO(1002,"验证码已过期，请重新发送验证码！");
        }
        //如果验证码输入正确
        if (pop.equals(code)){
            //修改密码
            int pwd = memberDao.updatePwd(memberId, newPwd);
            if (pwd>0) {
                return new ResultDTO(200,"修改成功");
            }
        }else {
            return new ResultDTO(1002,"验证码错误");
        }
        return new ResultDTO(1003,"修改失败");
    }


    @Override
    public ResultDTO sendEmail(Member member) {


        //给该用户发邮件
        MailDTO mailDTO = new MailDTO();
        //设置主题
        mailDTO.setSubject("修改密码的验证码！");
        String[] user = new String[1];
        user[0] = member.getMemberEmail();
        //设置收件人
        mailDTO.setTo(user);
        //设置抄送人
        String[] cc = new String[1];
        cc[0] = "377576540@qq.com";
        mailDTO.setCc(cc);
        //判断消息队列中是否已近存在
        if (!redisTemplate.hasKey("emailName:"+member.getMemberEmail())) {
            redisTemplate.opsForSet().add("emailName:"+member.getMemberEmail(), "email");
            //设置过期时间
            redisTemplate.expire("emailName:"+member.getMemberEmail(), 60, TimeUnit.SECONDS);
            // 发消息
            rocketMQTemplate.convertAndSend("user-email", mailDTO);
            return new ResultDTO(200, "发送成功", member.getMemberName());
        }
        return new ResultDTO(1001,"验证码未过期，请勿重新发送！");


    }


    /**
     * 修改员工所有信息
     */
    @Override
    public ResultDTO updateAll(Member member) {
        myValidator.validate(member,UserAdd.class);
        int update = memberDao.update(member);
        if (update>0) {
            return new ResultDTO(200,"修改成功");
        }
        return new ResultDTO(1001,"修改失败");
    }

    /**
     * 设置用户为常用旅客
     */
    @Override
    public ResultDTO updateIsUsual(Integer memberId, Integer isUsual) {
        int updateUsual = memberDao.updateUsual(memberId, isUsual);
        if (updateUsual>0) {
            return new ResultDTO(200,"修改成功");
        }
        return new ResultDTO(1001,"修改失败");
    }

    /**
     * 查询所有，不带分页
     * @return
     */
    @Override
    public ResultDTO findAllNoPage() {
        List<Member> allNoPage = memberDao.findAllNoPage();
        if (allNoPage != null) {
            return new ResultDTO(200,"查询成功",allNoPage);
        }
        return new ResultDTO(1001,"查询失败");
    }

    /**
     * 上传头像
     */
    @Override
    public ResultDTO updateImg(Integer memberId, MultipartFile file) {
        if (memberId == null || memberId == 0 || file == null){
            return new ResultDTO(1001,"上传参数不正确");
        }
        ResultDTO upload = uploadService.upload(file);
        System.out.println(upload.getData().toString());
        String data = (String) upload.getData();
        int updateImg = memberDao.updateImg(memberId, data);
        if (updateImg>0) {
            return new ResultDTO(200,"上传图片成功",memberId);
        }
        return new ResultDTO(1001,"上传图片失败");
    }


}
